package com.codechen.scaffold.news.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.codechen.scaffold.common.domain.UserInfo;
import com.codechen.scaffold.common.enums.ResultCodeEnum;
import com.codechen.scaffold.common.exception.BusinessException;
import com.codechen.scaffold.common.holder.UserInfoHolder;
import com.codechen.scaffold.common.util.BeanUtil;
import com.codechen.scaffold.news.constant.NewsStatusEnum;
import com.codechen.scaffold.news.domain.request.NewsQueryRequest;
import com.codechen.scaffold.news.domain.request.NewsSaveRequest;
import com.codechen.scaffold.news.domain.vo.NewsBaseVO;
import com.codechen.scaffold.news.domain.vo.NewsVO;
import com.codechen.scaffold.news.mapper.NewsMapper;
import com.codechen.scaffold.news.domain.entity.News;
import com.codechen.scaffold.news.service.INewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class NewsService extends ServiceImpl<NewsMapper, News> implements INewsService {

	@Autowired
	private NewsMapper newsMapper;

	@Override
	public void saveNews(NewsSaveRequest request, String status){
		News news = new News();
		if (Objects.nonNull(request.getId())) {
			news = newsMapper.selectById(request.getId());
			if (Objects.isNull(news)) {
				throw new BusinessException(ResultCodeEnum.FAIL.getCode(), "数据不存在");
			}
		}
		BeanUtil.copy(request, news);
		UserInfo userInfo = UserInfoHolder.getUserInfo();
		news.setStatus(status);
		news.setAuthorId(userInfo.getUserId());
		this.saveOrUpdate(news);
	}

	@Override
	public void removeNews(Long newsId) {
		this.removeById(newsId);
	}

	@Override
	public IPage<NewsBaseVO> queryList(Page<NewsBaseVO> newsPage, NewsQueryRequest newsQueryRequest) {
		return newsMapper.queryList(newsPage, newsQueryRequest);
	}

	@Override
	public NewsVO findNewsById(Long id) {
		News news = this.getById(id);
		NewsVO newsVO = new NewsVO();
		BeanUtil.copy(news, newsVO);
		return newsVO;
	}

	@Override
	public List<NewsBaseVO> listFeatures() {
		List<News> newsList = this.lambdaQuery().eq(News::getIsFeatured, 1).in(News::getStatus, Arrays.asList(NewsStatusEnum.PUBLISHED.getCode(), NewsStatusEnum.ARCHIVED.getCode())).list();
		List<NewsBaseVO> newsBaseVOList = new ArrayList<>();
		for (News news: newsList) {
			NewsBaseVO newsBaseVO = new NewsBaseVO();
			BeanUtil.copy(news, newsBaseVO);
			newsBaseVOList.add(newsBaseVO);
		}
		return newsBaseVOList;
	}



}
